<?php
/**
 * 春哥团队（www.cgtblog.com） - 春哥多端多商户万能DIY商城系统
 * Copyright © 2024 春哥技术团队 保留所有权利
 * =========================================================

 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 菜品
// +----------------------------------------------------------------------
namespace app\controller;

use app\model\RestaurantProductCategoryModel as Category;
use app\model\RestaurantProductModel;
use think\facade\Db;
use think\facade\View;

class RestaurantProduct extends Common
{
    public function initialize(){
        parent::initialize();
    }

    //菜品
    public function index()
    {
        if (request()->isAjax()) {
            $page = input('param.page');
            $limit = input('param.limit');

            if (input('param.field') && input('param.order')) {
                $order = input('param.field') . ' ' . input('param.order');
            } else {
                $order = 'sort desc,id desc';
            }
            $where[] = ['aid', '=', aid];
            if(bid==0){
                if(input('param.bid')){
                    $where[] = ['bid','=',input('param.bid')];
                }elseif(input('param.showtype')==2){
                    $where[] = ['bid','>',0];
                    $where[] = ['linkid','=',0];
                }elseif(input('param.showtype')=='all'){
                    $where[] = ['bid','>=',0];
                }elseif(input('param.showtype')==21){
                    $where[] = ['bid','=',-1];
                }else{
                    $where[] = ['bid','=',0];
                }
            }else{
                $where[] = ['bid','=',bid];
            }
            if(input('param.name')) $where[] = ['name','like','%'.$_GET['name'].'%'];
            if(input('?param.status') && input('param.status')!==''){
				$status = input('param.status');
				$nowtime = time();
				$nowhm = date('H:i');
				if($status==1){
					$where[] = Db::raw("`status`=1 or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime) or (`status`=3 and ((start_hours<end_hours and start_hours<='$nowhm' and end_hours>='$nowhm') or (start_hours>=end_hours and (start_hours<='$nowhm' or end_hours>='$nowhm'))) )");
				}else{
					$where[] = Db::raw("`status`=0 or (`status`=2 and (unix_timestamp(start_time)>$nowtime or unix_timestamp(end_time)<$nowtime)) or (`status`=3 and ((start_hours<end_hours and (start_hours>'$nowhm' or end_hours<'$nowhm')) or (start_hours>=end_hours and (start_hours>'$nowhm' and end_hours<'$nowhm'))) )");
				}
			}
            if(input('?get.cid') && input('param.cid')!=='') $where[] = Db::raw("find_in_set(".input('param.cid/d').",cid)");
            $data = (new RestaurantProductModel())->getList($where, $page, $limit, $order);
			$count = $data['count'];
			$list = $data['list'];
			foreach($list as $k=>$v){
				if($v['status']==2){ //设置上架时间
					if(strtotime($v['start_time']) <= time() && strtotime($v['end_time']) >= time()){
						$list[$k]['status'] = 1;
					}else{
						$list[$k]['status'] = 0;
					}
				}
				if($v['status']==3){ //设置上架周期
					$start_time = strtotime(date('Y-m-d '.$v['start_hours']));
					$end_time = strtotime(date('Y-m-d '.$v['end_hours']));
					if(($start_time < $end_time && $start_time <= time() && $end_time >= time()) || ($start_time >= $end_time && ($start_time <= time() || $end_time >= time()))){
						$list[$k]['status'] = 1;
					}else{
						$list[$k]['status'] = 0;
					}
				}
			}

            return json(['code' => 0, 'msg' => '查询成功', 'count' => $count, 'data' => $list]);
        }
        View::assign('rest_product_demo',0);
        //分类
        $clist = Db::name('restaurant_product_category')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',0)->order('sort desc,id')->select()->toArray();
        View::assign('clist',$clist);
        return View::fetch();
    }

    public function edit()
    {
        if(input('param.id')){
            $info = Db::name('restaurant_product')->where('aid',aid)->where('id',input('param.id/d'))->find();
            if(!$info) showmsg('商品不存在');
            if(bid != 0 && $info['bid']!=bid) showmsg('无权限操作');
            if(bid != 0 && $info['linkid']!=0) showmsg('无权限操作');
        }
        //多规格
        $guige_list = array();
        if($info){
            $gglist = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$info['id'])->select()->toArray();
            foreach($gglist as $k=>$v){
                $v['lvprice_data'] = json_decode($v['lvprice_data'],true);
                if($v['ks']!==null && $v['ks'] !== ''){
                    $guige_list[$v['ks']] = $v;
                }else{
                    Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$v['id'])->update(['ks'=>$k]);
                    $guige_list[$k] = $v;
                }
            }
            $info['cid'] = explode(',', $info['cid']);
            $info['status_week'] = explode(',', $info['status_week']);
        }else{
			$info = [];
			$info['status_week'] = ['1','2','3','4','5','6','7'];
		}
//        dump($guige_list);                                  
//        dump($newgglist);
        //分类
        $clist = Db::name('restaurant_product_category')->field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',0)->order('sort desc,id')->select()->toArray();
        $area_list = Db::name('restaurant_area')->field('id,name')->where('aid',aid)->where('bid',bid)->select()->toArray();
        $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
        $default_cid = $default_cid ? $default_cid : 0;
        $aglevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('can_agent','<>',0)->order('sort,id')->select()->toArray();
        $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
        $sysset = Db::name('admin_set')->where('aid',aid)->find();
        if($sysset['fxjiesuantype'] == 1) {
            $jiesuantypeDesc = '成交价';
        }elseif($sysset['fxjiesuantype'] == 2) {
            $jiesuantypeDesc = '销售利润';
        } else {
            $jiesuantypeDesc = '销售价';
        }
		$bset = Db::name('business_sysset')->where('aid',aid)->find();
        
        //加料
        View::assign('aglevellist',$aglevellist);
        View::assign('levellist',$levellist);
        View::assign('info',$info);
        View::assign('guige_list',$guige_list);
        View::assign('clist',$clist);
        View::assign('area_list',$area_list);
		View::assign('bset',$bset);
        View::assign('jiesuantypeDesc',$jiesuantypeDesc);
        return View::fetch();
    }

    //保存
    public function save(){
        if(input('post.id')){
            $product = Db::name('restaurant_product')->where('aid',aid)->where('id',input('post.id/d'))->find();
            if(!$product) showmsg('商品不存在');
            if(bid != 0 && $product['bid']!=bid) showmsg('无权限操作');
        }

        $info = input('post.info/a');
        $info['detail'] = \app\common\Common::geteditorcontent($info['detail']);
        if(!$info['pic']){
            if(bid > 0){
                $logo = Db::name('business')->where('aid',aid)->where('id',bid)->value('logo');
            }else{
                $logo = Db::name('admin_set')->where('aid',aid)->value('logo');
            }
            $info['pic'] = $logo;  
        }
        $data = array();
        $data['name'] = $info['name'];
        $data['pic'] = $info['pic'];
        $data['pics'] = $info['pics'];
        $data['sellpoint'] = $info['sellpoint'];
        $data['procode'] = $info['procode'];
        $data['cid'] = $info['cid'];
        $data['area_id'] = $info['area_id'];
        $data['freighttype'] = $info['freighttype'];
        $data['freightdata'] = $info['freightdata'];
        $data['commissionset'] = $info['commissionset'];
        $data['commissiondata1'] = jsonEncode(input('post.commissiondata1/a'));
        $data['commissiondata2'] = jsonEncode(input('post.commissiondata2/a'));
        $data['commissiondata3'] = jsonEncode(input('post.commissiondata3/a'));
		if(bid != 0){
			$bset = Db::name('business_sysset')->where('aid',aid)->find();
			if($bset['commission_canset']==0){
				$data['commissionset'] = '-1';
			}
		}
            $data['limit_per'] = $info['limit_per'];
        $data['scored_set'] = $info['scored_set'];
        $data['scored_val'] = $info['scored_val'];
        $data['limit_start'] = $info['limit_start'];
        $data['status_week'] = implode(',', $info['status_week']);
        if(isset($info['detail_text'])){
            $data['detail_text'] = $info['detail_text'];
        }
        if(isset($info['detail_pics'])){
            $data['detail_pics'] = $info['detail_pics'];
        }

        if($info['oldsales'] != $info['sales']){
            $data['sales'] = $info['sales'];
        }
        $data['sort'] = $info['sort'];
        $data['status'] = $info['status'];
		
		$data['start_time'] = $info['start_time'];
		$data['end_time'] = $info['end_time'];
		$data['start_hours'] = $info['start_hours'];
		$data['end_hours'] = $info['end_hours'];

        $data['detail'] = $info['detail'];
        if($info['gid']){
            $data['gid'] = implode(',',$info['gid']);
        }else{
            $data['gid'] = '';
        }

        $data['lvprice'] = $info['lvprice'];

        if($info['lvprice']==1){
            $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
            $default_cid = $default_cid ? $default_cid : 0;
            $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
            $defaultlvid = $levellist[0]['id'];
            $sellprice_field = 'sell_price_'.$defaultlvid;
        }else{
            $sellprice_field = 'sell_price';
        }
        $sell_price = 0;$market_price = 0;$cost_price = 0;$weight = 0;$givescore=0;$lvprice_data = [];
        foreach(input('post.option/a') as $ks=>$v){
            if($sell_price==0 || $v[$sellprice_field] < $sell_price){
                $sell_price = $v[$sellprice_field];
                $market_price = $v['market_price'];
                $cost_price = $v['cost_price'];
                $givescore = $v['givescore'];
                if($info['lvprice']==1){
                    $lvprice_data = [];
                    foreach($levellist as $lv){
                        $lvprice_data[$lv['id']] = $v['sell_price_'.$lv['id']];
                    }
                }
            }
        }
        if($info['lvprice']==1){
            $data['lvprice_data'] = json_encode($lvprice_data);
        }

        $data['market_price'] = $market_price;
        $data['cost_price'] = $cost_price;
        $data['sell_price'] = $sell_price;
        $data['pack_fee'] = $info['pack_fee'];
        $data['givescore'] = $givescore;
        $data['stock'] = 0;
        $data['stock_daily'] = 0;//每日库存
        foreach(input('post.option/a') as $v){
            $data['stock'] += $v['stock'];
            $data['stock_daily'] += $v['stock_daily'];
        }

        //多规格 规格项
        $data['guigedata'] = input('post.specs');
        
        //加料
        //        //[{"k":0,"title":"规格","items":[{"k":0,"title":"大码"},{"k":1,"title":"中码"},{"k":2,"title":"小"}]}]
//        $data['guigedata'] = [];
//        $dataGuige = [
//            "k" => 0,
//            "title" => '规格',
//            "items" => []
//        ];
        if($product){
            $table = new RestaurantProductModel();
            $table->where('aid',aid)->where('id',$product['id'])->save($data);
            $product_id = $product['id'];
            \app\common\System::plog(sprintf('餐饮菜品编辑:%s[%s]',$data['name'],$product_id));
        }else{
            $data['aid'] = aid;
            $data['bid'] = bid;
            if(bid == 0 && $info['bid']){
                $data['bid'] = $info['bid'];
                if($info['bid'] == -1) $data['sort'] = 1000000 + intval($data['sort']);
            }
            $table = new RestaurantProductModel();
            $table->save($data);
            $product_id = $table->id;
            \app\common\System::plog(sprintf('餐饮菜品添加:%s[%s]',$data['name'],$product_id));

            
			//菜品二维码 参数格式：id_1-cid_2
            //$path = 'pages/diancan/product';
            //$scene = ['id' => $product_id];
            //$qrcode = \app\common\Wechat::getQRCode(aid,'wx',$path,$scene);
            //if ($qrcode['status'] == 1 && $qrcode['url']) {
            //    $table->save(['qrcode' => $qrcode['url']]);
            //}
        }
        //更新商户虚拟销量
        if($product){
            $bid = $product['bid'];
        }else{
            $bid = $info['bid']?:bid;
        }
        $sales = $info['sales']-$info['oldsales'];
        if($sales!=0){
            \app\model\Payorder::addSales(0,'sales',aid,$bid,$sales);
        }
        //dump(input('post.option/a'));die;
        //多规格
        $newggids = array();
        foreach(input('post.option/a') as $ks=>$v){
            if (empty(trim($v['name']))) {
                continue;
            }
            $ggdata = array();
            $ggdata['product_id'] = $product_id;
            $ggdata['ks'] = $ks;
            $ggdata['name'] = $v['name'];
            $ggdata['pic'] = $v['pic'] ? $v['pic'] : '';
            $ggdata['market_price'] = $v['market_price']>0 ? $v['market_price']:0;
            $ggdata['cost_price'] = $v['cost_price']>0 ? $v['cost_price']:0;
            $ggdata['sell_price'] = $v['sell_price']>0 ? $v['sell_price']:0;
            $ggdata['procode'] = $v['procode'];
            $ggdata['barcode'] = $v['barcode'];
            $ggdata['givescore'] = $v['givescore'];
            $ggdata['stock'] = $v['stock']>0 ? $v['stock']:0;
            $ggdata['stock_daily'] = $v['stock_daily']>0 ? $v['stock_daily']:0;
            $lvprice_data = [];
            //会员价格
            if($info['lvprice']==1){
                $ggdata['sell_price'] = $v['sell_price_'.$levellist[0]['id']]>0 ? $v['sell_price_'.$levellist[0]['id']]:0;
                foreach($levellist as $lv){
                    $sell_price = $v['sell_price_'.$lv['id']]>0 ? $v['sell_price_'.$lv['id']]:0;
                    $lvprice_data[$lv['id']] = $sell_price;
                }
                $ggdata['lvprice_data'] = json_encode($lvprice_data);
            }

            $guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product_id)->where('ks',$ks)->find();
            if($guige){
                Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$guige['id'])->update($ggdata);
                $ggid = $guige['id'];
            }else{
                $ggdata['aid'] = aid;
                $ggid = Db::name('restaurant_product_guige')->insertGetId($ggdata);
            }

            $newggids[] = $ggid;
//            $dataGuige['items'][] = [
//                "k" => $ks,
//                "title" => $v['name']
//            ];
        }
        Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product_id)->where('id','not in',$newggids)->delete();
//        $data['guigedata'] = json_encode([$dataGuige]);
        $table = new RestaurantProductModel();
        $table->where('aid',aid)->where('id',$product_id)->save($data);
        //删除多余规格
        Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product_id)->where('id','not in',$newggids)->delete();
        $this->tongbuproduct($product_id);
        return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index')]);

    }

    //改状态
    public function setst(){
        $st = input('post.st/d');
        $ids = input('post.ids/a');
        $where = [];
        $where[] = ['aid','=',aid];
        $where[] = ['id','in',$ids];
        if(bid !=0){
            $where[] = ['bid','=',bid];
            $where[] = ['linkid','=',0];
        }
        Db::name('restaurant_product')->where($where)->update(['status'=>$st]);
        $this->tongbuproduct($ids);
        \app\common\System::plog('餐饮菜品改状态'.implode(',',$ids));
        return json(['status'=>1,'msg'=>'操作成功']);
    }
    //删除
    public function del(){
        $ids = input('post.ids/a');
        if(!$ids) $ids = array(input('post.id/d'));
        $where = [];
        $where[] = ['aid','=',aid];
        $where[] = ['id','in',$ids];
        if(bid !=0){
            $where[] = ['bid','=',bid];
            $where[] = ['linkid','=',0];
        }
        $prolist = Db::name('restaurant_product')->where($where)->select();
        foreach($prolist as $pro) {
            $where2 = [];
            $where2[] = ['aid','=',aid];
            if(bid !=0){
                $where2[] = ['bid','=',bid];
            }
            if(bid>0 && $pro['linkid']>0){
                return json(['status'=>0,'msg'=>'默认菜品不能删除']);break;
            }
            Db::name('restaurant_product')->where($where2)->where('id', $pro['id'])->delete();
            Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id', $pro['id'])->delete();
            }

        \app\common\System::plog('餐饮菜品删除'.implode(',',$ids));
        return json(['status'=>1,'msg'=>'删除成功']);
    }
    //复制商品
    public function procopy(){
        $product = Db::name('restaurant_product')->where('aid',aid)->where('id',input('post.id/d'))->find();
        if(!$product) return json(['status'=>0,'msg'=>'商品不存在,请重新选择']);
        if(bid != 0 && $product['bid']!=bid) showmsg('无权限操作');
        if(bid != 0 && $product['linkid']!=0) showmsg('无权限操作');
        $gglist = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product['id'])->select()->toArray();
        $data = $product;
        $data['name'] = '复制-'.$data['name'];
        unset($data['id']);
        $data['status'] = 0;
        $newproid = Db::name('restaurant_product')->insertGetId($data);
        foreach($gglist as $gg){
            $ggdata = $gg;
            $ggdata['product_id'] = $newproid;
            unset($ggdata['id']);
            Db::name('restaurant_product_guige')->insert($ggdata);
        }
        //        $this->tongbuproduct($newproid);
        \app\common\System::plog('餐饮菜品复制'.$newproid);
        return json(['status'=>1,'msg'=>'复制成功','product_id'=>$newproid]);
    }
	//选择商品
	public function chooseproduct(){
		//分类
		$clist = Db::name('restaurant_product_category')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',0)->order('sort desc,id')->select()->toArray(); 
		foreach($clist as $k=>$v){
			$clist[$k]['child'] = Db::name('restaurant_product_category')->Field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',$v['id'])->order('sort desc,id')->select()->toArray(); 
		}
		View::assign('clist',$clist);
		return View::fetch();
	}
	//获取商品信息
	public function getproduct(){
		$proid = input('post.proid/d');
		$product = Db::name('restaurant_product')->where('aid',aid)->where('id',$proid)->find();
		//多规格
		$newgglist = array();
		$gglist = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product['id'])->select()->toArray();
		foreach($gglist as $k=>$v){
			$newgglist[$v['ks']] = $v;
		}
		$guigedata = json_decode($product['guigedata']);
		return json(['product'=>$product,'gglist'=>$newgglist,'guigedata'=>$guigedata]);
	}

    public function editCommon()
    {
        if(input('param.id')){
            $info = Db::name('restaurant_product')->where('aid',aid)->where('bid',bid)->where('id',input('param.id/d'))->find();
        }
        //多规格
        $guige_list = array();
        if($info){
            $gglist = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$info['id'])->select()->toArray();
            foreach($gglist as $k=>$v){
                $v['lvprice_data'] = json_decode($v['lvprice_data'],true);
                if($v['ks']!==null && $v['ks'] !== ''){
                    $guige_list[$v['ks']] = $v;
                }else{
                    Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$v['id'])->update(['ks'=>$k]);
                    $guige_list[$k] = $v;
                }
            }
            $info['cid'] = explode(',', $info['cid']);
            $info['status_week'] = explode(',', $info['status_week']);
        }else{
            $info = [];
            $info['status_week'] = ['1','2','3','4','5','6','7'];
        }

//        dump($guige_list);
//        dump($newgglist);
        //分类
        $clist = Db::name('restaurant_product_category')->field('id,name')->where('aid',aid)->where('bid',bid)->where('pid',0)->order('sort desc,id')->select()->toArray();
        $area_list = Db::name('restaurant_area')->field('id,name')->where('aid',aid)->where('bid',bid)->select()->toArray();
        $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
        $default_cid = $default_cid ? $default_cid : 0;
        $aglevellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->where('can_agent','<>',0)->order('sort,id')->select()->toArray();
        $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
        $sysset = Db::name('admin_set')->where('aid',aid)->find();
        if($sysset['fxjiesuantype'] == 1) {
            $jiesuantypeDesc = '成交价';
        }elseif($sysset['fxjiesuantype'] == 2) {
            $jiesuantypeDesc = '销售利润';
        } else {
            $jiesuantypeDesc = '销售价';
        }

        $bset = Db::name('business_sysset')->where('aid',aid)->find();
        View::assign('aglevellist',$aglevellist);
        View::assign('levellist',$levellist);
        View::assign('info',$info);
        View::assign('guige_list',$guige_list);
        View::assign('clist',$clist);
        View::assign('area_list',$area_list);
        View::assign('bset',$bset);
        View::assign('jiesuantypeDesc',$jiesuantypeDesc);
        return View::fetch();
    }

    //保存
    public function saveCommon(){
        if(input('post.id'))
            $product = Db::name('restaurant_product')->where('aid',aid)->where('bid',bid)->where('id',input('post.id/d'))->find();
        $info = input('post.info/a');
        $data = array();
        $data['cid'] = $info['cid'];
        $data['area_id'] = $info['area_id'];

//        $data['limit_per'] = $info['limit_per'];
//        $data['scored_set'] = $info['scored_set'];
//        $data['scored_val'] = $info['scored_val'];
//        $data['limit_start'] = $info['limit_start'];
//        $data['status_week'] = implode(',', $info['status_week']);
//        if(isset($info['detail_text'])){
//            $data['detail_text'] = $info['detail_text'];
//        }
//        if(isset($info['detail_pics'])){
//            $data['detail_pics'] = $info['detail_pics'];
//        }
//
//        if($info['oldsales'] != $info['sales']){
//            $data['sales'] = $info['sales'];
//        }
        $data['sort'] = $info['sort'];
//        $data['status'] = $info['status'];

//        $data['start_time'] = $info['start_time'];
//        $data['end_time'] = $info['end_time'];
//        $data['start_hours'] = $info['start_hours'];
//        $data['end_hours'] = $info['end_hours'];
//
//        $data['detail'] = $info['detail'];
//        if($info['gid']){
//            $data['gid'] = implode(',',$info['gid']);
//        }else{
//            $data['gid'] = '';
//        }

//        $data['lvprice'] = $info['lvprice'];

        if($info['lvprice']==1){
            $default_cid = Db::name('member_level_category')->where('aid',aid)->where('isdefault', 1)->value('id');
            $default_cid = $default_cid ? $default_cid : 0;
            $levellist = Db::name('member_level')->where('aid',aid)->where('cid', $default_cid)->order('sort,id')->select()->toArray();
            $defaultlvid = $levellist[0]['id'];
            $sellprice_field = 'sell_price_'.$defaultlvid;
        }else{
            $sellprice_field = 'sell_price';
        }
        $sell_price = 0;$market_price = 0;$cost_price = 0;$weight = 0;$givescore=0;$lvprice_data = [];
        foreach(input('post.option/a') as $ks=>$v){
            if($sell_price==0 || $v[$sellprice_field] < $sell_price){
                $sell_price = $v[$sellprice_field];
                $market_price = $v['market_price'];
                $cost_price = $v['cost_price'];
                $givescore = $v['givescore'];
                if($info['lvprice']==1){
                    $lvprice_data = [];
                    foreach($levellist as $lv){
                        $lvprice_data[$lv['id']] = $v['sell_price_'.$lv['id']];
                    }
                }
            }
        }
        if($info['lvprice']==1){
            $data['lvprice_data'] = json_encode($lvprice_data);
        }

//        $data['market_price'] = $market_price;
//        $data['cost_price'] = $cost_price;
        $data['sell_price'] = $sell_price;
//        $data['pack_fee'] = $info['pack_fee'];
//        $data['givescore'] = $givescore;
        $data['stock'] = 0;
        $data['stock_daily'] = 0;//每日库存
        foreach(input('post.option/a') as $v){
            $data['stock'] += $v['stock'];
            $data['stock_daily'] += $v['stock_daily'];
        }

        //多规格 规格项
        //[{"k":0,"title":"规格","items":[{"k":0,"title":"大码"},{"k":1,"title":"中码"},{"k":2,"title":"小"}]}]
        $data['guigedata'] = [];
        $dataGuige = [
            "k" => 0,
            "title" => '规格',
            "items" => []
        ];

        if($product){
            $table = new RestaurantProductModel();
            $table->where('aid',aid)->where('id',$product['id'])->save($data);
            $product_id = $product['id'];
            \app\common\System::plog(sprintf('餐饮菜品编辑:%s[%s]',$data['name'],$product_id));
        }else{
            $data['aid'] = aid;
            $data['bid'] = bid;
            if(bid == 0 && $info['bid']){
                $data['bid'] = $info['bid'];
                if($info['bid'] == -1) $data['sort'] = 1000000 + intval($data['sort']);
            }
            $table = new RestaurantProductModel();
            $table->save($data);
            $product_id = $table->id;
            \app\common\System::plog(sprintf('餐饮菜品添加:%s[%s]',$data['name'],$product_id));


            //菜品二维码 参数格式：id_1-cid_2
            //$path = 'pages/diancan/product';
            //$scene = ['id' => $product_id];
            //$qrcode = \app\common\Wechat::getQRCode(aid,'wx',$path,$scene);
            //if ($qrcode['status'] == 1 && $qrcode['url']) {
            //    $table->save(['qrcode' => $qrcode['url']]);
            //}
        }
        //dump(input('post.option/a'));die;
        //多规格
        $newggids = array();
        foreach(input('post.option/a') as $ks=>$v){
            if (empty(trim($v['name']))) {
                continue;
            }
            $ggdata = array();
            $ggdata['product_id'] = $product_id;
//            $ggdata['ks'] = $ks;
//            $ggdata['name'] = $v['name'];
//            $ggdata['pic'] = $v['pic'] ? $v['pic'] : '';
//            $ggdata['market_price'] = $v['market_price']>0 ? $v['market_price']:0;
//            $ggdata['cost_price'] = $v['cost_price']>0 ? $v['cost_price']:0;
            $ggdata['sell_price'] = $v['sell_price']>0 ? $v['sell_price']:0;
//            $ggdata['procode'] = $v['procode'];
//            $ggdata['givescore'] = $v['givescore'];
            $ggdata['stock'] = $v['stock']>0 ? $v['stock']:0;
            $ggdata['stock_daily'] = $v['stock_daily']>0 ? $v['stock_daily']:0;
            $lvprice_data = [];
            //会员价格
            if($info['lvprice']==1){
                $ggdata['sell_price'] = $v['sell_price_'.$levellist[0]['id']]>0 ? $v['sell_price_'.$levellist[0]['id']]:0;
                foreach($levellist as $lv){
                    $sell_price = $v['sell_price_'.$lv['id']]>0 ? $v['sell_price_'.$lv['id']]:0;
                    $lvprice_data[$lv['id']] = $sell_price;
                }
                $ggdata['lvprice_data'] = json_encode($lvprice_data);
            }

            $guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product_id)->where('ks',$ks)->find();
            if($guige){
                Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$guige['id'])->update($ggdata);
                $ggid = $guige['id'];
            }else{
                $ggdata['aid'] = aid;
                $ggid = Db::name('restaurant_product_guige')->insertGetId($ggdata);
            }

            $newggids[] = $ggid;
            $dataGuige['items'][] = [
                "k" => $ks,
                "title" => $v['name']
            ];
        }
        $data['guigedata'] = json_encode([$dataGuige]);
        $table = new RestaurantProductModel();
        $table->where('aid',aid)->where('id',$product_id)->save($data);

        //删除多余规格
        Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product_id)->where('id','not in',$newggids)->delete();
        $this->tongbuproduct($product_id);
        return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index')]);

    }

    public function setCommon()
    {
        if(!getcustom('rest_product_demo')){
            return;
        }
        $id = input('post.id/d');
        //先添加，后同步
        $product = Db::name('restaurant_product')->where('aid',aid)->where('id',$id)->find();
        if($product){
            unset($product['id']);
            $product['bid'] = -1;
            $product['create_time'] = time();
            $product['sort'] = 1000000 + intval($product['sort']);
            $newproid = Db::name('restaurant_product')->where('aid',aid)->insertGetId($product);
            $guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$id)->select()->toArray();
            if($guige){
                foreach ($guige as $item) {
                    unset($item['id']);
                    $item['product_id'] = $newproid;
                    Db::name('restaurant_product_guige')->insert($item);
                }
            }
            $this->tongbuproduct($newproid);
        }
        return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index')]);
    }

    //同步商品到商户
    private function tongbuproduct($proids){
        if(!getcustom('rest_product_demo')){
            return;
        }
        if(!is_array($proids)){
            $proids = explode(',',$proids);
        }
        $blist = [];
        foreach($proids as $proid){
            $product = Db::name('restaurant_product')->where('aid',aid)->where('id',$proid)->find();
            if($product && $product['bid'] == -1){
                $gglist = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$product['id'])->select()->toArray();
                if(!$blist){
                    $blist = Db::name('business')->where('aid',aid)->order('sort desc,id desc')->select()->toArray();
                }
                foreach($blist as $business){
                    $bpro = Db::name('restaurant_product')->where('aid',aid)->where('bid',$business['id'])->where('linkid',$product['id'])->find();
                    $data = $product;
                    $data['bid'] = $business['id'];
                    $data['linkid'] = $product['id'];
                    unset($data['id']); unset($data['cid']); unset($data['area_id']);
                    if($bpro){
                        Db::name('restaurant_product')->where('id',$bpro['id'])->update($data);
                        $newproid = $bpro['id'];
                    }else{
                        $newproid = Db::name('restaurant_product')->insertGetId($data);
                    }

                    $newggids = [];
                    foreach($gglist as $gg){
                        $ggdata = $gg;
                        $ggdata['product_id'] = $newproid;
                        unset($ggdata['id']);

                        $guige = Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$newproid)->where('ks',$ggdata['ks'])->find();
                        if($guige){
                            Db::name('restaurant_product_guige')->where('aid',aid)->where('id',$guige['id'])->update($ggdata);
                            $ggid = $guige['id'];
                        }else{
                            $ggid = Db::name('restaurant_product_guige')->insertGetId($ggdata);
                        }
                        $newggids[] = $ggid;
                    }
                    Db::name('restaurant_product_guige')->where('aid',aid)->where('product_id',$newproid)->where('id','not in',$newggids)->delete();
                }
            }
        }
    }
    //平台下店铺列表
    public function getBusinessListByAid(){
        }
    //平台下店铺列表
    public function getBusinessCategoryList(){
        }
    //导入菜品
    public function importRestaurant(){
        }
}